﻿Imports ACompany.OrderProcessing.Infrastructure
Imports NHibernate

Public Class NhibernateUnitOfWork
    Implements IUnitOfWork

    Private _Session As ISession

    Public Sub New()
        _Session = SessionFactory.GetCurrentSession
    End Sub

    Public Sub Save(ByVal Entity As IAggregateRoot) Implements IUnitOfWork.Save
        'TODO: Use CurrentSession, this will be from the HttpContext
        _Session.SaveOrUpdate(Entity)
    End Sub

    Public Sub Commit() Implements IUnitOfWork.Commit

        Using transaction = _Session.BeginTransaction
            Try

                transaction.Commit() ' flush the session and commit the transaction

            Catch NHex As StaleObjectStateException
                transaction.Rollback()
                ' TODO: Log exception

                ' Catch StaleObjectStateException:
                ' Entity was changed while we were viewing it, 
                ' Wrap Nhibernate exception  and then send it 
                ' back up the calling stack 
                Throw New ConcurrencyException("Please reload the screen as changes have been made to an entity since first viewing.", NHex)

            Catch ex As Exception
                transaction.Rollback()
                ' TODO: Log exception
                Throw
            End Try

        End Using

    End Sub

    Public Sub Delete(ByVal Entity As IAggregateRoot) Implements IUnitOfWork.Delete
        _Session.Delete(Entity)
    End Sub

End Class
